package com.flaskpy.web.eternity.log.config;


import com.flaskpy.web.eternity.log.aspect.LogAscept;
import com.flaskpy.web.eternity.log.entity.LogServerProperties;
import com.flaskpy.web.eternity.log.service.IAopLogService;
import com.flaskpy.web.eternity.log.service.impl.AopLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@ConditionalOnWebApplication    //条件web环境
@ConditionalOnClass(value = AopLogService.class)    //条件类加载器
@EnableConfigurationProperties({LogServerProperties.class})     //加载配置
@ConditionalOnProperty(prefix = "aoplogservice",name = "enabled",matchIfMissing = true) //日志是否开启
public class AutoConfiguration {

    @Autowired
    private LogServerProperties logServerProperties;

    @Bean
    @ConditionalOnMissingBean(value = IAopLogService.class) //默认ben
    public IAopLogService aopLogService(){

        return new AopLogService();
    }
    @Bean
    public LogAscept logAscept(){   //日志aop
        return new LogAscept();   //!!!里面调用了IAopLogService
    }

    /**
     * 日志线程池
     * @return
     */
    @Bean("aopLogThreadPoll")
    @ConditionalOnMissingBean(name ="aopLogThreadPoll" )
    public ThreadPoolTaskExecutor aopLogThreadPoll(){
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(this.logServerProperties.getCorePollSize());       //初始化线程(不会关闭)
        taskExecutor.setMaxPoolSize(logServerProperties.getMaxPoolSize());        //最大线程
        taskExecutor.setQueueCapacity(logServerProperties.getQueuecapcity());  //最大队列
        taskExecutor.setKeepAliveSeconds(logServerProperties.getKeepAliveSeconds());   //最大空闲时间(秒)
        taskExecutor.setThreadNamePrefix(logServerProperties.getThreadNamePrefix());
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

}
